package com.bookstore.back.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.bookstore.back.common.Result;
import com.bookstore.back.entity.*;
import com.bookstore.back.service.*;
import com.bookstore.back.entity.Bestseller;
import com.bookstore.back.vo.ReviewVO;
import com.bookstore.back.util.UserContextUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * 后台管理控制器
 * 
 * @author 程序猿_Ti
 * @since 2025-07-19
 */
@Slf4j
@RestController
@RequestMapping("/admin")
public class AdminController {

    @Autowired
    private AdminService adminService;
    
    @Autowired
    private UserService userService;
    
    @Autowired
    private BookService bookService;
    
    @Autowired
    private CategoryService categoryService;

    @Autowired
    private TagService tagService;

    @Autowired
    private OrderService orderService;
    
    @Autowired
    private NewsService newsService;

    @Autowired
    private NewsCategoryRelationService newsCategoryRelationService;

    @Autowired
    private NewsCategoryService newsCategoryService;
    
    @Autowired
    private ReviewService reviewService;

    @Autowired
    private BestsellerService bestsellerService;

    @Autowired
    private BestsellerScheduleService bestsellerScheduleService;

    @Autowired
    private UserLogService userLogService;

    @Autowired
    private UserContextUtil userContextUtil;

    // ==================== 仪表盘相关 ====================
    
    /**
     * 获取仪表盘统计数据
     */
    @GetMapping("/dashboard/stats")
    public Result<Map<String, Object>> getDashboardStats() {
        try {
            Map<String, Object> stats = adminService.getDashboardStats();
            return Result.success(stats);
        } catch (Exception e) {
            log.error("获取仪表盘统计数据失败：{}", e.getMessage());
            return Result.error("获取统计数据失败");
        }
    }

    /**
     * 获取最近订单
     */
    @GetMapping("/dashboard/recent-orders")
    public Result<List<Order>> getRecentOrders(@RequestParam(defaultValue = "15") Integer limit) {
        try {
            List<Order> orders = orderService.getRecentOrders(limit);
            return Result.success(orders);
        } catch (Exception e) {
            log.error("获取最近订单失败：{}", e.getMessage());
            return Result.error("获取最近订单失败");
        }
    }

    /**
     * 获取热门图书
     */
    @GetMapping("/dashboard/popular-books")
    public Result<List<Book>> getPopularBooks(@RequestParam(defaultValue = "10") Integer limit) {
        try {
            List<Book> books = bookService.getPopularBooks(limit);
            return Result.success(books);
        } catch (Exception e) {
            log.error("获取热门图书失败：{}", e.getMessage());
            return Result.error("获取热门图书失败");
        }
    }

    /**
     * 获取销售趋势数据
     */
    @GetMapping("/dashboard/sales-trend")
    public Result<Map<String, Object>> getSalesTrend() {
        try {
            Map<String, Object> trendData = adminService.getSalesTrend();
            return Result.success(trendData);
        } catch (Exception e) {
            log.error("获取销售趋势数据失败：{}", e.getMessage());
            return Result.error("获取销售趋势数据失败");
        }
    }

    /**
     * 获取分类销售占比数据
     */
    @GetMapping("/dashboard/category-sales")
    public Result<List<Map<String, Object>>> getCategorySales() {
        try {
            List<Map<String, Object>> categoryData = adminService.getCategorySales();
            return Result.success(categoryData);
        } catch (Exception e) {
            log.error("获取分类销售数据失败：{}", e.getMessage());
            return Result.error("获取分类销售数据失败");
        }
    }

    // ==================== 用户管理 ====================
    
    /**
     * 获取用户列表
     */
    @GetMapping("/users")
    public Result<IPage<User>> getUserList(@RequestParam Map<String, Object> params) {
        try {
            IPage<User> userPage = userService.getUserList(params);
            return Result.success(userPage);
        } catch (Exception e) {
            log.error("获取用户列表失败：{}", e.getMessage());
            return Result.error("获取用户列表失败");
        }
    }

    /**
     * 创建用户
     */
    @PostMapping("/users")
    public Result<String> createUser(@RequestBody User user) {
        try {
            log.info("接收到创建用户请求，用户数据：username={}, roleId={}", user.getUsername(), user.getRoleId());
            boolean success = userService.createUser(user);
            return success ? Result.success("创建用户成功") : Result.error("创建用户失败");
        } catch (Exception e) {
            log.error("创建用户失败：{}", e.getMessage());
            return Result.error("创建用户失败：" + e.getMessage());
        }
    }

    /**
     * 更新用户
     */
    @PutMapping("/users/{userId}")
    public Result<String> updateUser(@PathVariable Long userId, @RequestBody User user) {
        try {
            boolean success = userService.updateUser(userId, user);
            return success ? Result.success("更新用户成功") : Result.error("更新用户失败");
        } catch (Exception e) {
            log.error("更新用户失败：{}", e.getMessage());
            return Result.error("更新用户失败：" + e.getMessage());
        }
    }

    /**
     * 删除用户
     */
    @DeleteMapping("/users/{userId}")
    public Result<String> deleteUser(@PathVariable Long userId) {
        try {
            boolean success = userService.deleteUser(userId);
            return success ? Result.success("删除用户成功") : Result.error("删除用户失败");
        } catch (Exception e) {
            log.error("删除用户失败：{}", e.getMessage());
            return Result.error("删除用户失败：" + e.getMessage());
        }
    }

    /**
     * 切换用户状态
     */
    @PatchMapping("/users/{userId}/status")
    public Result<String> toggleUserStatus(@PathVariable Long userId, @RequestBody Map<String, Integer> params) {
        try {
            Integer status = params.get("status");
            boolean success = userService.toggleUserStatus(userId, status);
            return success ? Result.success("切换用户状态成功") : Result.error("切换用户状态失败");
        } catch (Exception e) {
            log.error("切换用户状态失败：{}", e.getMessage());
            return Result.error("切换用户状态失败：" + e.getMessage());
        }
    }

    /**
     * 批量删除用户
     */
    @DeleteMapping("/users/batch")
    public Result<String> batchDeleteUsers(@RequestBody Map<String, List<Long>> params) {
        try {
            List<Long> userIds = params.get("ids");
            boolean success = userService.batchDeleteUsers(userIds);
            return success ? Result.success("批量删除用户成功") : Result.error("批量删除用户失败");
        } catch (Exception e) {
            log.error("批量删除用户失败：{}", e.getMessage());
            return Result.error("批量删除用户失败：" + e.getMessage());
        }
    }

    // ==================== 图书管理 ====================
    
    /**
     * 获取图书列表
     */
    @GetMapping("/books")
    public Result<IPage<Book>> getBookList(@RequestParam Map<String, Object> params) {
        try {
            IPage<Book> bookPage = bookService.getBookList(params);
            return Result.success(bookPage);
        } catch (Exception e) {
            log.error("获取图书列表失败：{}", e.getMessage());
            return Result.error("获取图书列表失败");
        }
    }

    /**
     * 创建图书
     */
    @PostMapping("/books")
    public Result<String> createBook(@RequestBody Book book) {
        try {
            boolean success = bookService.createBook(book);
            return success ? Result.success("创建图书成功") : Result.error("创建图书失败");
        } catch (Exception e) {
            log.error("创建图书失败：{}", e.getMessage());
            return Result.error("创建图书失败：" + e.getMessage());
        }
    }

    /**
     * 更新图书
     */
    @PutMapping("/books/{bookId}")
    public Result<String> updateBook(@PathVariable Integer bookId, @RequestBody Book book) {
        try {
            boolean success = bookService.updateBook(bookId, book);
            return success ? Result.success("更新图书成功") : Result.error("更新图书失败");
        } catch (Exception e) {
            log.error("更新图书失败：{}", e.getMessage());
            return Result.error("更新图书失败：" + e.getMessage());
        }
    }

    /**
     * 删除图书
     */
    @DeleteMapping("/books/{bookId}")
    public Result<String> deleteBook(@PathVariable Integer bookId) {
        try {
            boolean success = bookService.deleteBook(bookId);
            return success ? Result.success("删除图书成功") : Result.error("删除图书失败");
        } catch (Exception e) {
            log.error("删除图书失败：{}", e.getMessage());
            return Result.error("删除图书失败：" + e.getMessage());
        }
    }

    /**
     * 获取图书详情（包含标签）
     */
    @GetMapping("/books/{bookId}")
    public Result<Book> getBookDetail(@PathVariable Integer bookId) {
        try {
            Book book = bookService.getBookWithTags(bookId);
            return book != null ? Result.success(book) : Result.error("图书不存在");
        } catch (Exception e) {
            log.error("获取图书详情失败：{}", e.getMessage());
            return Result.error("获取图书详情失败");
        }
    }

    /**
     * 更新图书标签
     */
    @PutMapping("/books/{bookId}/tags")
    public Result<String> updateBookTags(@PathVariable Integer bookId, @RequestBody Map<String, Object> request) {
        try {
            @SuppressWarnings("unchecked")
            List<Integer> tagIds = (List<Integer>) request.get("tagIds");
            boolean success = bookService.updateBookTags(bookId, tagIds);
            return success ? Result.success("更新图书标签成功") : Result.error("更新图书标签失败");
        } catch (Exception e) {
            log.error("更新图书标签失败：{}", e.getMessage());
            return Result.error("更新图书标签失败：" + e.getMessage());
        }
    }

    /**
     * 切换图书状态
     */
    @PatchMapping("/books/{bookId}/status")
    public Result<String> toggleBookStatus(@PathVariable Integer bookId, @RequestBody Map<String, Integer> params) {
        try {
            Integer status = params.get("status");
            boolean success = bookService.toggleBookStatus(bookId, status);
            return success ? Result.success("切换图书状态成功") : Result.error("切换图书状态失败");
        } catch (Exception e) {
            log.error("切换图书状态失败：{}", e.getMessage());
            return Result.error("切换图书状态失败：" + e.getMessage());
        }
    }

    /**
     * 批量删除图书
     */
    @DeleteMapping("/books/batch")
    public Result<String> batchDeleteBooks(@RequestBody Map<String, List<Integer>> params) {
        try {
            List<Integer> bookIds = params.get("ids");
            boolean success = bookService.batchDeleteBooks(bookIds);
            return success ? Result.success("批量删除图书成功") : Result.error("批量删除图书失败");
        } catch (Exception e) {
            log.error("批量删除图书失败：{}", e.getMessage());
            return Result.error("批量删除图书失败：" + e.getMessage());
        }
    }

    // ==================== 分类管理 ====================

    /**
     * 获取分类列表
     */
    @GetMapping("/categories")
    public Result<IPage<BookCategory>> getCategoryList(@RequestParam Map<String, Object> params) {
        try {
            IPage<BookCategory> categoryPage = categoryService.getCategoryList(params);
            return Result.success(categoryPage);
        } catch (Exception e) {
            log.error("获取分类列表失败：{}", e.getMessage());
            return Result.error("获取分类列表失败");
        }
    }

    /**
     * 创建分类
     */
    @PostMapping("/categories")
    public Result<String> createCategory(@RequestBody BookCategory category) {
        try {
            boolean success = categoryService.createCategory(category);
            return success ? Result.success("创建分类成功") : Result.error("创建分类失败");
        } catch (Exception e) {
            log.error("创建分类失败：{}", e.getMessage());
            return Result.error("创建分类失败：" + e.getMessage());
        }
    }

    /**
     * 更新分类
     */
    @PutMapping("/categories/{categoryId}")
    public Result<String> updateCategory(@PathVariable Integer categoryId, @RequestBody BookCategory category) {
        try {
            boolean success = categoryService.updateCategory(categoryId, category);
            return success ? Result.success("更新分类成功") : Result.error("更新分类失败");
        } catch (Exception e) {
            log.error("更新分类失败：{}", e.getMessage());
            return Result.error("更新分类失败：" + e.getMessage());
        }
    }

    /**
     * 删除分类
     */
    @DeleteMapping("/categories/{categoryId}")
    public Result<String> deleteCategory(@PathVariable Integer categoryId) {
        try {
            boolean success = categoryService.deleteCategory(categoryId);
            return success ? Result.success("删除分类成功") : Result.error("删除分类失败");
        } catch (Exception e) {
            log.error("删除分类失败：{}", e.getMessage());
            return Result.error("删除分类失败：" + e.getMessage());
        }
    }

    /**
     * 切换分类状态
     */
    @PatchMapping("/categories/{categoryId}/status")
    public Result<String> toggleCategoryStatus(@PathVariable Integer categoryId, @RequestBody Map<String, Integer> params) {
        try {
            Integer status = params.get("status");
            boolean success = categoryService.toggleCategoryStatus(categoryId, status);
            return success ? Result.success("切换分类状态成功") : Result.error("切换分类状态失败");
        } catch (Exception e) {
            log.error("切换分类状态失败：{}", e.getMessage());
            return Result.error("切换分类状态失败：" + e.getMessage());
        }
    }

    // ==================== 标签管理 ====================

    /**
     * 获取标签列表
     */
    @GetMapping("/tags")
    public Result<IPage<BookTag>> getTagList(@RequestParam Map<String, Object> params) {
        try {
            IPage<BookTag> tagPage = tagService.getTagList(params);
            return Result.success(tagPage);
        } catch (Exception e) {
            log.error("获取标签列表失败：{}", e.getMessage());
            return Result.error("获取标签列表失败");
        }
    }

    /**
     * 获取所有标签
     */
    @GetMapping("/tags/all")
    public Result<List<BookTag>> getAllTags() {
        try {
            List<BookTag> tags = tagService.getAllTags();
            return Result.success(tags);
        } catch (Exception e) {
            log.error("获取所有标签失败：{}", e.getMessage());
            return Result.error("获取所有标签失败");
        }
    }

    /**
     * 创建标签
     */
    @PostMapping("/tags")
    public Result<String> createTag(@RequestBody BookTag tag) {
        try {
            boolean success = tagService.createTag(tag);
            return success ? Result.success("创建标签成功") : Result.error("创建标签失败");
        } catch (Exception e) {
            log.error("创建标签失败：{}", e.getMessage());
            return Result.error("创建标签失败：" + e.getMessage());
        }
    }

    /**
     * 更新标签
     */
    @PutMapping("/tags/{tagId}")
    public Result<String> updateTag(@PathVariable Integer tagId, @RequestBody BookTag tag) {
        try {
            boolean success = tagService.updateTag(tagId, tag);
            return success ? Result.success("更新标签成功") : Result.error("更新标签失败");
        } catch (Exception e) {
            log.error("更新标签失败：{}", e.getMessage());
            return Result.error("更新标签失败：" + e.getMessage());
        }
    }

    /**
     * 删除标签
     */
    @DeleteMapping("/tags/{tagId}")
    public Result<String> deleteTag(@PathVariable Integer tagId) {
        try {
            boolean success = tagService.deleteTag(tagId);
            return success ? Result.success("删除标签成功") : Result.error("删除标签失败");
        } catch (Exception e) {
            log.error("删除标签失败：{}", e.getMessage());
            return Result.error("删除标签失败：" + e.getMessage());
        }
    }

    // ==================== 订单管理 ====================

    /**
     * 获取订单列表
     */
    @GetMapping("/orders")
    public Result<IPage<Order>> getOrderList(@RequestParam Map<String, Object> params) {
        try {
            IPage<Order> orderPage = orderService.getOrderList(params);
            return Result.success(orderPage);
        } catch (Exception e) {
            log.error("获取订单列表失败：{}", e.getMessage());
            return Result.error("获取订单列表失败");
        }
    }

    /**
     * 获取订单详情
     */
    @GetMapping("/orders/{orderId}")
    public Result<Map<String, Object>> getOrderDetail(@PathVariable Integer orderId) {
        try {
            Map<String, Object> orderDetail = orderService.getOrderDetail(orderId);
            return orderDetail != null ? Result.success(orderDetail) : Result.error("订单不存在");
        } catch (Exception e) {
            log.error("获取订单详情失败：{}", e.getMessage());
            return Result.error("获取订单详情失败");
        }
    }

    /**
     * 更新订单状态
     */
    @PatchMapping("/orders/{orderId}/status")
    public Result<String> updateOrderStatus(@PathVariable Integer orderId, @RequestBody Map<String, Integer> params) {
        try {
            Integer status = params.get("status");
            boolean success = orderService.updateOrderStatus(orderId, status);
            return success ? Result.success("更新订单状态成功") : Result.error("更新订单状态失败");
        } catch (Exception e) {
            log.error("更新订单状态失败：{}", e.getMessage());
            return Result.error("更新订单状态失败：" + e.getMessage());
        }
    }

    /**
     * 发货处理
     */
    @PostMapping("/orders/{orderId}/ship")
    public Result<String> shipOrder(@PathVariable Integer orderId) {
        try {
            boolean success = orderService.shipOrder(orderId);
            return success ? Result.success("发货成功") : Result.error("发货失败");
        } catch (Exception e) {
            log.error("发货失败：{}", e.getMessage());
            return Result.error("发货失败：" + e.getMessage());
        }
    }

    /**
     * 取消订单
     */
    @PostMapping("/orders/{orderId}/cancel")
    public Result<String> cancelOrder(@PathVariable Integer orderId, @RequestBody Map<String, String> params) {
        try {
            String reason = params.get("reason");
            boolean success = orderService.cancelOrder(orderId, reason);
            return success ? Result.success("取消订单成功") : Result.error("取消订单失败");
        } catch (Exception e) {
            log.error("取消订单失败：{}", e.getMessage());
            return Result.error("取消订单失败：" + e.getMessage());
        }
    }

    // ==================== 新闻管理 ====================

    /**
     * 获取新闻列表
     */
    @GetMapping("/news")
    public Result<IPage<News>> getNewsList(@RequestParam Map<String, Object> params) {
        try {
            IPage<News> newsPage = newsService.getNewsList(params);

            // 为每个新闻填充分类信息
            newsPage.getRecords().forEach(news -> {
                List<Integer> categoryIds = newsCategoryRelationService.getCategoryIdsByNewsId(news.getId());
                news.setCategoryIds(categoryIds);
            });

            return Result.success(newsPage);
        } catch (Exception e) {
            log.error("获取新闻列表失败：{}", e.getMessage());
            return Result.error("获取新闻列表失败");
        }
    }

    /**
     * 创建新闻
     */
    @PostMapping("/news")
    public Result<String> createNews(@RequestBody News news) {
        try {
            boolean success = newsService.createNews(news);
            return success ? Result.success("创建新闻成功") : Result.error("创建新闻失败");
        } catch (Exception e) {
            log.error("创建新闻失败：{}", e.getMessage());
            return Result.error("创建新闻失败：" + e.getMessage());
        }
    }

    /**
     * 更新新闻
     */
    @PutMapping("/news/{newsId}")
    public Result<String> updateNews(@PathVariable Integer newsId, @RequestBody News news) {
        try {
            boolean success = newsService.updateNews(newsId, news);
            return success ? Result.success("更新新闻成功") : Result.error("更新新闻失败");
        } catch (Exception e) {
            log.error("更新新闻失败：{}", e.getMessage());
            return Result.error("更新新闻失败：" + e.getMessage());
        }
    }

    /**
     * 删除新闻
     */
    @DeleteMapping("/news/{newsId}")
    public Result<String> deleteNews(@PathVariable Integer newsId) {
        try {
            boolean success = newsService.deleteNews(newsId);
            return success ? Result.success("删除新闻成功") : Result.error("删除新闻失败");
        } catch (Exception e) {
            log.error("删除新闻失败：{}", e.getMessage());
            return Result.error("删除新闻失败：" + e.getMessage());
        }
    }

    /**
     * 切换新闻状态
     */
    @PatchMapping("/news/{newsId}/status")
    public Result<String> toggleNewsStatus(@PathVariable Integer newsId, @RequestBody Map<String, Integer> params) {
        try {
            Integer status = params.get("status");
            boolean success = newsService.toggleNewsStatus(newsId, status);
            return success ? Result.success("切换新闻状态成功") : Result.error("切换新闻状态失败");
        } catch (Exception e) {
            log.error("切换新闻状态失败：{}", e.getMessage());
            return Result.error("切换新闻状态失败：" + e.getMessage());
        }
    }

    /**
     * 切换新闻推荐状态
     */
    @PatchMapping("/news/{newsId}/recommended")
    public Result<String> toggleNewsRecommended(@PathVariable Integer newsId, @RequestBody Map<String, Integer> params) {
        try {
            Integer isRecommended = params.get("isRecommended");
            boolean success = newsService.toggleNewsRecommended(newsId, isRecommended);
            return success ? Result.success("切换推荐状态成功") : Result.error("切换推荐状态失败");
        } catch (Exception e) {
            log.error("切换推荐状态失败：{}", e.getMessage());
            return Result.error("切换推荐状态失败：" + e.getMessage());
        }
    }

    /**
     * 批量删除新闻
     */
    @DeleteMapping("/news/batch")
    public Result<String> batchDeleteNews(@RequestBody Map<String, List<Integer>> params) {
        try {
            List<Integer> newsIds = params.get("ids");
            boolean success = newsService.batchDeleteNews(newsIds);
            return success ? Result.success("批量删除新闻成功") : Result.error("批量删除新闻失败");
        } catch (Exception e) {
            log.error("批量删除新闻失败：{}", e.getMessage());
            return Result.error("批量删除新闻失败：" + e.getMessage());
        }
    }

    /**
     * 创建新闻分类
     */
    @PostMapping("/news/categories")
    public Result<NewsCategory> createNewsCategory(@RequestBody NewsCategory newsCategory) {
        try {
            // 检查分类名称是否已存在
            if (newsCategoryService.isNameExists(newsCategory.getName())) {
                return Result.error("分类已存在，请重新填写！");
            }

            // 设置默认值
            if (newsCategory.getStatus() == null) {
                newsCategory.setStatus(1); // 默认启用
            }
            if (newsCategory.getSortOrder() == null) {
                newsCategory.setSortOrder(0); // 默认排序
            }

            boolean success = newsCategoryService.save(newsCategory);
            if (success) {
                return Result.success(newsCategory);
            } else {
                return Result.error("创建分类失败");
            }
        } catch (Exception e) {
            log.error("创建新闻分类失败：{}", e.getMessage());
            return Result.error("创建分类失败：" + e.getMessage());
        }
    }

    // ==================== 评论管理 ====================

    /**
     * 获取评论列表
     */
    @GetMapping("/reviews")
    public Result<IPage<ReviewVO>> getReviewList(@RequestParam Map<String, Object> params) {
        try {
            IPage<ReviewVO> reviewPage = reviewService.getReviewList(params);
            return Result.success(reviewPage);
        } catch (Exception e) {
            log.error("获取评论列表失败：{}", e.getMessage());
            return Result.error("获取评论列表失败");
        }
    }

    /**
     * 获取评论详情
     */
    @GetMapping("/reviews/{reviewId}")
    public Result<Map<String, Object>> getReviewDetail(@PathVariable Integer reviewId) {
        try {
            Map<String, Object> reviewDetail = reviewService.getReviewDetail(reviewId);
            return reviewDetail != null ? Result.success(reviewDetail) : Result.error("评论不存在");
        } catch (Exception e) {
            log.error("获取评论详情失败：{}", e.getMessage());
            return Result.error("获取评论详情失败");
        }
    }

    /**
     * 更新评论
     */
    @PutMapping("/reviews/{reviewId}")
    public Result<String> updateReview(@PathVariable Integer reviewId, @RequestBody Map<String, Object> reviewData) {
        try {
            boolean success = reviewService.updateReview(reviewId, reviewData);
            return success ? Result.success("更新评论成功") : Result.error("更新评论失败");
        } catch (Exception e) {
            log.error("更新评论失败：{}", e.getMessage());
            return Result.error("更新评论失败：" + e.getMessage());
        }
    }

    /**
     * 删除评论
     */
    @DeleteMapping("/reviews/{reviewId}")
    public Result<String> deleteReview(@PathVariable Integer reviewId) {
        try {
            boolean success = reviewService.deleteReview(reviewId);
            return success ? Result.success("删除评论成功") : Result.error("删除评论失败");
        } catch (Exception e) {
            log.error("删除评论失败：{}", e.getMessage());
            return Result.error("删除评论失败：" + e.getMessage());
        }
    }

    /**
     * 切换评论状态
     */
    @PatchMapping("/reviews/{reviewId}/status")
    public Result<String> toggleReviewStatus(@PathVariable Integer reviewId, @RequestBody Map<String, Integer> params) {
        try {
            Integer status = params.get("status");
            boolean success = reviewService.toggleReviewStatus(reviewId, status);
            return success ? Result.success("切换评论状态成功") : Result.error("切换评论状态失败");
        } catch (Exception e) {
            log.error("切换评论状态失败：{}", e.getMessage());
            return Result.error("切换评论状态失败：" + e.getMessage());
        }
    }

    /**
     * 批量删除评论
     */
    @DeleteMapping("/reviews/batch")
    public Result<String> batchDeleteReviews(@RequestBody Map<String, List<Integer>> params) {
        try {
            List<Integer> reviewIds = params.get("ids");
            boolean success = reviewService.batchDeleteReviews(reviewIds);
            return success ? Result.success("批量删除评论成功") : Result.error("批量删除评论失败");
        } catch (Exception e) {
            log.error("批量删除评论失败：{}", e.getMessage());
            return Result.error("批量删除评论失败：" + e.getMessage());
        }
    }

    // ==================== 文件上传 ====================

    /**
     * 文件上传
     */
    @PostMapping("/upload")
    public Result<Map<String, Object>> uploadFile(@RequestParam("file") MultipartFile file,
                                                   @RequestParam(value = "type", defaultValue = "image") String type) {
        try {
            if (file.isEmpty()) {
                return Result.error("上传文件不能为空");
            }

            // 检查文件类型
            String originalFilename = file.getOriginalFilename();
            if (originalFilename == null) {
                return Result.error("文件名不能为空");
            }

            String fileExtension = originalFilename.substring(originalFilename.lastIndexOf(".")).toLowerCase();
            if (!isValidImageExtension(fileExtension)) {
                return Result.error("只支持 jpg、jpeg、png、gif 格式的图片");
            }

            // 检查文件大小 (2MB)
            if (file.getSize() > 20 * 1024 * 1024) {
                return Result.error("文件大小不能超过 20MB");
            }

            // 创建上传目录
            String uploadDir = "uploads/" + type + "/" + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy/MM/dd"));
            Path uploadPath = Paths.get(uploadDir);
            if (!Files.exists(uploadPath)) {
                Files.createDirectories(uploadPath);
            }

            // 生成新的文件名
            String newFileName = UUID.randomUUID().toString() + fileExtension;
            Path filePath = uploadPath.resolve(newFileName);

            // 保存文件
            Files.copy(file.getInputStream(), filePath);

            // 构建返回的文件URL
            String fileUrl = "/" + uploadDir + "/" + newFileName;

            Map<String, Object> result = new HashMap<>();
            result.put("url", fileUrl);
            result.put("originalName", originalFilename);
            result.put("size", file.getSize());
            result.put("type", file.getContentType());

            log.info("文件上传成功：{}", fileUrl);
            return Result.success("文件上传成功", result);

        } catch (IOException e) {
            log.error("文件上传失败：{}", e.getMessage());
            return Result.error("文件上传失败：" + e.getMessage());
        } catch (Exception e) {
            log.error("文件上传异常：{}", e.getMessage());
            return Result.error("文件上传失败");
        }
    }

    /**
     * 验证图片文件扩展名
     */
    private boolean isValidImageExtension(String extension) {
        String[] validExtensions = {".jpg", ".jpeg", ".png", ".gif"};
        for (String validExt : validExtensions) {
            if (validExt.equals(extension)) {
                return true;
            }
        }
        return false;
    }

    // ==================== 畅销管理 ====================

    /**
     * 获取畅销榜单列表
     */
    @GetMapping("/bestsellers")
    public Result<IPage<Bestseller>> getBestsellerList(@RequestParam Map<String, Object> params) {
        try {
            IPage<Bestseller> bestsellerPage = bestsellerService.getBestsellerList(params);
            return Result.success(bestsellerPage);
        } catch (Exception e) {
            log.error("获取畅销榜单列表失败：{}", e.getMessage());
            return Result.error("获取畅销榜单列表失败");
        }
    }

    /**
     * 创建畅销榜单记录
     */
    @PostMapping("/bestsellers")
    public Result<String> createBestseller(@RequestBody Bestseller bestseller) {
        try {
            boolean success = bestsellerService.createBestseller(bestseller);
            return success ? Result.success("添加畅销图书成功") : Result.error("添加畅销图书失败");
        } catch (Exception e) {
            log.error("添加畅销图书失败：{}", e.getMessage());
            return Result.error("添加畅销图书失败：" + e.getMessage());
        }
    }

    /**
     * 更新畅销榜单信息
     */
    @PutMapping("/bestsellers/{bestsellerId}")
    public Result<String> updateBestseller(@PathVariable Integer bestsellerId, @RequestBody Bestseller bestseller) {
        try {
            boolean success = bestsellerService.updateBestseller(bestsellerId, bestseller);
            return success ? Result.success("更新畅销榜单成功") : Result.error("更新畅销榜单失败");
        } catch (Exception e) {
            log.error("更新畅销榜单失败：{}", e.getMessage());
            return Result.error("更新畅销榜单失败：" + e.getMessage());
        }
    }

    /**
     * 删除畅销榜单记录
     */
    @DeleteMapping("/bestsellers/{bestsellerId}")
    public Result<String> deleteBestseller(@PathVariable Integer bestsellerId) {
        try {
            boolean success = bestsellerService.deleteBestseller(bestsellerId);
            return success ? Result.success("移除畅销图书成功") : Result.error("移除畅销图书失败");
        } catch (Exception e) {
            log.error("移除畅销图书失败：{}", e.getMessage());
            return Result.error("移除畅销图书失败：" + e.getMessage());
        }
    }

    /**
     * 批量更新排名
     */
    @PatchMapping("/bestsellers/ranks")
    public Result<String> updateBestsellerRanks(@RequestBody Map<String, List<Map<String, Object>>> params) {
        try {
            List<Map<String, Object>> updates = params.get("updates");
            boolean success = bestsellerService.updateBestsellerRanks(updates);
            return success ? Result.success("批量更新排名成功") : Result.error("批量更新排名失败");
        } catch (Exception e) {
            log.error("批量更新排名失败：{}", e.getMessage());
            return Result.error("批量更新排名失败：" + e.getMessage());
        }
    }

    /**
     * 获取可添加到畅销榜的图书列表
     */
    @GetMapping("/bestsellers/available-books")
    public Result<List<Book>> getAvailableBooks(@RequestParam Map<String, Object> params) {
        try {
            List<Book> books = bestsellerService.getAvailableBooks(params);
            return Result.success(books);
        } catch (Exception e) {
            log.error("获取可用图书列表失败：{}", e.getMessage());
            return Result.error("获取可用图书列表失败");
        }
    }

    @GetMapping("/bestsellers/generate")
    public Result<String> generateBestsellerRankings() {
        try {
            bestsellerScheduleService.generateBestsellerRankings();
            return Result.success("畅销榜单生成成功");
        } catch (Exception e) {
            log.error("生成畅销榜单失败：{}", e.getMessage());
            return Result.error("生成畅销榜单失败：" + e.getMessage());
        }
    }

    // ==================== 管理员个人资料 ====================

    /**
     * 获取管理员个人资料
     */
    @GetMapping("/profile")
    public Result<Map<String, Object>> getAdminProfile() {
        try {
            Map<String, Object> profile = adminService.getAdminProfile();
            return Result.success(profile);
        } catch (Exception e) {
            log.error("获取管理员个人资料失败：{}", e.getMessage());
            return Result.error("获取个人资料失败");
        }
    }

    /**
     * 更新管理员个人资料
     */
    @PutMapping("/profile")
    public Result<String> updateAdminProfile(@RequestBody Map<String, Object> profileData) {
        try {
            boolean success = adminService.updateAdminProfile(profileData);
            return success ? Result.success("更新个人资料成功") : Result.error("更新个人资料失败");
        } catch (Exception e) {
            log.error("更新管理员个人资料失败：{}", e.getMessage());
            return Result.error("更新个人资料失败：" + e.getMessage());
        }
    }

    /**
     * 修改管理员密码
     */
    @PutMapping("/password")
    public Result<String> changeAdminPassword(@RequestBody Map<String, String> passwordData) {
        try {
            boolean success = adminService.changeAdminPassword(passwordData);
            return success ? Result.success("密码修改成功") : Result.error("密码修改失败");
        } catch (Exception e) {
            log.error("修改管理员密码失败：{}", e.getMessage());
            return Result.error("密码修改失败：" + e.getMessage());
        }
    }

    /**
     * 获取管理员统计信息
     */
    @GetMapping("/profile/stats")
    public Result<Map<String, Object>> getAdminStats() {
        try {
            Map<String, Object> stats = adminService.getAdminStats();

            // 记录操作日志
            try {
                // 获取当前登录用户ID
                Long currentUserId = userContextUtil.getCurrentUserId();
                if (currentUserId != null) {
                    userLogService.recordOperationLog(currentUserId, "查看个人统计信息");
                }
            } catch (Exception logException) {
                log.warn("记录操作日志失败：{}", logException.getMessage());
            }

            return Result.success(stats);
        } catch (Exception e) {
            log.error("获取管理员统计信息失败：{}", e.getMessage());
            return Result.error("获取统计信息失败");
        }
    }

    /**
     * 上传管理员头像
     */
    @PostMapping("/profile/avatar")
    public Result<Map<String, Object>> uploadAvatar(@RequestParam("file") MultipartFile file) {
        try {
            if (file.isEmpty()) {
                return Result.error("上传文件不能为空");
            }

            // 检查文件类型
            String originalFilename = file.getOriginalFilename();
            if (originalFilename == null) {
                return Result.error("文件名不能为空");
            }

            String fileExtension = originalFilename.substring(originalFilename.lastIndexOf(".")).toLowerCase();
            if (!isValidImageExtension(fileExtension)) {
                return Result.error("只支持 jpg、jpeg、png、gif 格式的图片");
            }

            // 检查文件大小 (2MB)
            if (file.getSize() > 2 * 1024 * 1024) {
                return Result.error("文件大小不能超过 2MB");
            }

            // 创建上传目录
            String uploadDir = "uploads/avatar/" + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy/MM/dd"));
            Path uploadPath = Paths.get(uploadDir);
            if (!Files.exists(uploadPath)) {
                Files.createDirectories(uploadPath);
            }

            // 生成新的文件名
            String newFileName = UUID.randomUUID().toString() + fileExtension;
            Path filePath = uploadPath.resolve(newFileName);

            // 保存文件
            Files.copy(file.getInputStream(), filePath);

            // 构建返回的文件URL
            String fileUrl = "/" + uploadDir + "/" + newFileName;

            // 更新用户头像
            boolean updateSuccess = adminService.updateAdminAvatar(fileUrl);
            if (!updateSuccess) {
                return Result.error("更新头像失败");
            }

            Map<String, Object> result = new HashMap<>();
            result.put("url", fileUrl);
            result.put("originalName", originalFilename);
            result.put("size", file.getSize());

            log.info("管理员头像上传成功：{}", fileUrl);
            return Result.success("头像上传成功", result);

        } catch (IOException e) {
            log.error("头像上传失败：{}", e.getMessage());
            return Result.error("头像上传失败：" + e.getMessage());
        } catch (Exception e) {
            log.error("头像上传异常：{}", e.getMessage());
            return Result.error("头像上传失败");
        }
    }

}
